from django.contrib import admin
from .models import Product, HotRecommend
from sku.models import Sku, skuAndAttribute, attribute
from category.admin import CategoryInline

# 属性内联
class AttributeInline(admin.TabularInline):
    model = skuAndAttribute
    extra = 0
    autocomplete_fields = ['attribute']


# SKU内联,需要嵌套内联的类需要使用admin.TabularInline
class SkuInline(admin.TabularInline):
    model = Sku
    extra = 0
    inlines = [AttributeInline]  # 嵌套属性内联
    fields = ('price', 'stock', 'image', 'original_price')
    show_change_link = True


# 商品主管理
class ProductAdmin(admin.ModelAdmin):
    inlines = [SkuInline]  # 包含SKU内联
    list_display = ('name', 'display_skus', 'cover_preview')
    search_fields = ('name', 'description')
    list_filter = ('category',)

    # 自定义字段显示所有SKU
    def display_skus(self, obj):
        return ", ".join([f"{sku.price}元" for sku in obj.sku_set.all()])

    display_skus.short_description = 'SKU价格'

    # 封面图片预览
    def cover_preview(self, obj):
        return obj.cover.url if obj.cover else ''

    cover_preview.short_description = '封面预览'
    cover_preview.allow_tags = True


admin.site.register(Product, ProductAdmin)
admin.site.register(HotRecommend)

